/*
 *  Copyright 2009 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fs.mybatis.core.generator.mybatis3;

import java.util.ArrayList;
import java.util.List;

import com.fs.mybatis.core.api.GeneratedJavaFile;
import com.fs.mybatis.core.api.GeneratedXmlFile;
import com.fs.mybatis.core.api.IntrospectedTable;
import com.fs.mybatis.core.api.dom.java.CompilationUnit;
import com.fs.mybatis.core.api.dom.xml.Document;
import com.fs.mybatis.core.generator.AbstractGenerator;
import com.fs.mybatis.core.generator.AbstractJavaClientGenerator;
import com.fs.mybatis.core.generator.AbstractJavaGenerator;
import com.fs.mybatis.core.generator.AbstractXmlGenerator;
import com.fs.mybatis.core.generator.config.PropertyRegistry;
import com.fs.mybatis.core.generator.internal.ObjectFactory;
import com.fs.mybatis.core.generator.mybatis3.javamapper.JavaMapperGenerator;
import com.fs.mybatis.core.generator.mybatis3.model.BaseRecordGenerator;
import com.fs.mybatis.core.generator.mybatis3.model.PrimaryKeyGenerator;
import com.fs.mybatis.core.generator.mybatis3.model.RecordWithBLOBsGenerator;
import com.fs.mybatis.core.generator.mybatis3.xmlmapper.XMLMapperGenerator;

/**
 * 
 * @author Jeff Butler
 * 
 */
public class IntrospectedTableMyBatis3Impl extends IntrospectedTable {
    protected List<AbstractJavaGenerator> javaModelGenerators;
    protected List<AbstractJavaGenerator> javaBasicModelGenerators;
    protected List<AbstractJavaGenerator> clientGenerators;
    protected AbstractXmlGenerator xmlMapperGenerator;

    public IntrospectedTableMyBatis3Impl() {
        super(TargetRuntime.MYBATIS3);
        javaModelGenerators = new ArrayList<AbstractJavaGenerator>();
        clientGenerators = new ArrayList<AbstractJavaGenerator>();
        javaBasicModelGenerators = new ArrayList<AbstractJavaGenerator>();
    }

    @Override
    public void calculateGenerators() {
        calculateJavaModelGenerators();

        AbstractJavaClientGenerator javaClientGenerator = calculateClientGenerators();

        calculateXmlMapperGenerator(javaClientGenerator);
    }

    protected void calculateXmlMapperGenerator(AbstractJavaClientGenerator javaClientGenerator) {
        if (javaClientGenerator == null) {
            if (context.getSqlMapGeneratorConfiguration() != null) {
                xmlMapperGenerator = new XMLMapperGenerator();
            }
        } else {
            xmlMapperGenerator = javaClientGenerator.getMatchedXMLGenerator();
        }

        initializeAbstractGenerator(xmlMapperGenerator);
    }

    /**
     * 
     * @param warnings
     * @param progressCallback
     * @return true if an XML generator is required
     */
    protected AbstractJavaClientGenerator calculateClientGenerators() {
        if (!rules.generateJavaClient()) {
            return null;
        }

        AbstractJavaClientGenerator javaGenerator = createJavaClientGenerator();
        if (javaGenerator == null) {
            return null;
        }

        initializeAbstractGenerator(javaGenerator);
        clientGenerators.add(javaGenerator);

        return javaGenerator;
    }

    protected AbstractJavaClientGenerator createJavaClientGenerator() {
        if (context.getJavaClientGeneratorConfiguration() == null) {
            return null;
        }

        String type = context.getJavaClientGeneratorConfiguration().getConfigurationType();

        AbstractJavaClientGenerator javaGenerator;
        if ("XMLMAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$
            javaGenerator = new JavaMapperGenerator();
        } else if ("MAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$
            javaGenerator = new JavaMapperGenerator();
        } else {
            javaGenerator = (AbstractJavaClientGenerator) ObjectFactory.createInternalObject(type);
        }

        return javaGenerator;
    }

    protected void calculateJavaModelGenerators() {
        if (getRules().generatePrimaryKeyClass()) {
            AbstractJavaGenerator javaGenerator = new PrimaryKeyGenerator();
            initializeAbstractGenerator(javaGenerator);
            javaModelGenerators.add(javaGenerator);
        }

        if (getRules().generateBaseRecordClass()) {
            AbstractJavaGenerator javaGenerator = new BaseRecordGenerator();
            initializeAbstractGenerator(javaGenerator);
            javaModelGenerators.add(javaGenerator);
        }

        if (getRules().generateRecordWithBLOBsClass()) {
            AbstractJavaGenerator javaGenerator = new RecordWithBLOBsGenerator();
            initializeAbstractGenerator(javaGenerator);
            javaModelGenerators.add(javaGenerator);
        }
    }

    protected void initializeAbstractGenerator(AbstractGenerator abstractGenerator) {
        if (abstractGenerator == null) {
            return;
        }

        abstractGenerator.setContext(context);
        abstractGenerator.setIntrospectedTable(this);
    }

    @Override
    public List<GeneratedJavaFile> getGeneratedJavaFiles() {
        List<GeneratedJavaFile> answer = new ArrayList<GeneratedJavaFile>();

        for (AbstractJavaGenerator javaGenerator : javaModelGenerators) {
            List<CompilationUnit> compilationUnits = javaGenerator.getCompilationUnits();
            for (CompilationUnit compilationUnit : compilationUnits) {
                GeneratedJavaFile gjf =
                        new GeneratedJavaFile(compilationUnit, context.getJavaModelGeneratorConfiguration()
                                .getTargetProject(), context.getProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING),
                                context.getJavaFormatter());
                answer.add(gjf);
            }
        }
        
        for (AbstractJavaGenerator javaGenerator : javaBasicModelGenerators) {
            List<CompilationUnit> compilationUnits = javaGenerator.getCompilationUnits();
            for (CompilationUnit compilationUnit : compilationUnits) {
                GeneratedJavaFile gjf =
                        new GeneratedJavaFile(compilationUnit, context.getJavaBasicModelGeneratorConfiguration()
                                .getTargetProject(), context.getProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING),
                                context.getJavaFormatter());
                answer.add(gjf);
            }
        }

        for (AbstractJavaGenerator javaGenerator : clientGenerators) {
            List<CompilationUnit> compilationUnits = javaGenerator.getCompilationUnits();
            for (CompilationUnit compilationUnit : compilationUnits) {
                GeneratedJavaFile gjf =
                        new GeneratedJavaFile(compilationUnit, context.getJavaClientGeneratorConfiguration()
                                .getTargetProject(), context.getProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING),
                                context.getJavaFormatter());
                answer.add(gjf);
            }
        }
        return answer;
    }

    
    

    @Override
    public List<GeneratedXmlFile> getGeneratedXmlFiles() {
        List<GeneratedXmlFile> answer = new ArrayList<GeneratedXmlFile>();

        if (xmlMapperGenerator != null) {
            Document documentWriteDao = xmlMapperGenerator.getDocumentWriteDao();
            Document documentDao = xmlMapperGenerator.getDocumentDao();
            
            GeneratedXmlFile gxfwritedao =
                    new GeneratedXmlFile(documentWriteDao, getMyBatis3XmlMapperFileName(), getMyBatis3XmlMapperPackage(),
                            context.getSqlMapGeneratorConfiguration().getTargetProject(), true,
                            context.getXmlFormatter());

            GeneratedXmlFile gxfdao =
                    new GeneratedXmlFile(documentDao, getMyBatis3XmlMapperFileNameDao(), getMyBatis3XmlMapperPackage(),
                            context.getSqlMapGeneratorConfiguration().getTargetProject(), true,
                            context.getXmlFormatter());

            answer.add(gxfwritedao);
            answer.add(gxfdao);
        }

        return answer;
    }

    @Override
    public int getGenerationSteps() {
        return javaModelGenerators.size() + clientGenerators.size() + (xmlMapperGenerator == null ? 0 : 1);
    }

    @Override
    public boolean isJava5Targeted() {
        return true;
    }

    @Override
    public boolean requiresXMLGenerator() {
        AbstractJavaClientGenerator javaClientGenerator = createJavaClientGenerator();

        if (javaClientGenerator == null) {
            return false;
        } else {
            return javaClientGenerator.requiresXMLGenerator();
        }
    }
}
